package com.usian.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.fast_dfs.FastDFSClient;
import com.usian.model.common.base.BaseServiceImpl;
import com.usian.model.common.dtos.PageResponseResult;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.media.dtos.WmMaterialDto;
import com.usian.model.media.pojos.WmMaterial;
import com.usian.model.media.pojos.WmNewsMaterial;
import com.usian.model.media.pojos.WmUser;
import com.usian.utils.threadlocal.WmThreadLocalUtils;
import com.usian.wemedia.mapper.WmMaterialMapper;
import com.usian.wemedia.mapper.WmNewsMaterialMapper;
import com.usian.wemedia.service.WmMaterialService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class WmMaterialServiceImpl extends BaseServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Autowired
    FastDFSClient fastDFSClient;

    @Value("${fdfs.url}")
    private String fileServerUrl;//资源服务器的域名


    @Override
    public ResponseResult uploadPicture(MultipartFile file) {
        //1.检查参数  对前台用户传入的文件进行空判
        if(file == null){
            return paramError;
        }

        //2.上传图片到FastDFS(资源管理模块)
        String fileId = null;
        try {
            fileId = fastDFSClient.uploadFile(file);//将传入file上传到FastDFS
        } catch (IOException e) {
            e.printStackTrace();
            return serverError;
        }

        //3.保存素材数据到表中 wm_material(自媒体图文素材信息表)

        WmUser user =  WmThreadLocalUtils.getUser();//获取当前登录信息的自媒体用户信息

        WmMaterial wmMaterial = new WmMaterial();//图文素材对象
        wmMaterial.setUrl(fileId);               //fileId为FastDFS中的文件地址
        wmMaterial.setIsCollection((short)0);    //首次添加为未收藏
        wmMaterial.setUserId(user.getId());      //关联自媒体用户Id
        wmMaterial.setType((short)0);            //素材类型
        wmMaterial.setCreatedTime(new Date());   //创建日期
        save(wmMaterial);                        //添加进wm_material表
        //拼接图片路径
        wmMaterial.setUrl(fileServerUrl+fileId);        //给用户返回一个可以访问到文件的地址
        return ResponseResult.okResult(wmMaterial);
    }

    @Override
    public ResponseResult findList(WmMaterialDto dto) {
        //1.检查参数   此处已经设置默认分页的相关条件(page=*,size=*)

        //2.带条件分页查询
        LambdaQueryWrapper<WmMaterial> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        //获取当前线程中已经登录的自媒体用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        lambdaQueryWrapper.eq(WmMaterial::getUserId,uid);//lambdaQueryWrapper方式查询  根据自媒体用户ID
        //是否收藏  根据收藏状态查询
        if(dto.getIsCollection() != null && dto.getIsCollection().shortValue()==1){
            lambdaQueryWrapper.eq(WmMaterial::getIsCollection,dto.getIsCollection());
        }
        //按照日期倒序排序
        lambdaQueryWrapper.orderByDesc(WmMaterial::getCreatedTime);
        IPage pageParam = new Page(dto.getPage(),dto.getSize());//分页条件
        IPage resultPage = page(pageParam, lambdaQueryWrapper);//分页条件+分页对象
        //3.结果返回
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),(int)resultPage.getTotal());
        List<WmMaterial> datas = resultPage.getRecords();
        //为每个图片加上前缀
//        datas.forEach(d->d.url() = fileServerUrl+d.getUrl());
        datas = datas.stream().map(item->{
            item.setUrl(fileServerUrl+item.getUrl());
            return item;
        }).collect(Collectors.toList());
        responseResult.setData(datas);

        return responseResult;
    }

    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;


    @Override
    public ResponseResult delPicture(Integer id) {//删除图片素材
        //1.检查参数  对当前素材的Id进行空判
        if(id == null){
            return paramError;
        }

        //2.根据素材Id判断自媒体图文素材信息表是否存在该素材
        WmMaterial wmMaterial = getById(id);
        if(wmMaterial == null){
            return paramError;
        }
        LambdaQueryWrapper<WmNewsMaterial> lambdaQueryWrapper = new LambdaQueryWrapper();
        lambdaQueryWrapper.eq(WmNewsMaterial::getMaterialId,id);
        /*
        * 自媒体图文引用素材信息查询：
        *         若查询到结果的数量>0:处于被引用状态，则不可删除
        *         若查询到结果的数量<0:处于非引用状态，则可删除
        * */
        Integer count = wmNewsMaterialMapper.selectCount(lambdaQueryWrapper);
        if(count > 0){
            return paramError.error(501,"当前图片被引用");
        }
        //3.删除fastdfs中的图片(做了一个替换字符串操作---将拼接路径替换为空串)
        String fileId = wmMaterial.getUrl().replace(fileServerUrl, "");
        try {
            fastDFSClient.delFile(fileId);
        }catch (Exception e){
            e.printStackTrace();
            return serverError;
        }
        //4.删除数据库中的图片
        removeById(id);
        return okResult;
    }

    @Override
    public ResponseResult updateStatus(Integer id, Short type) {
        //1.检查参数   对传入素材Id以及若收藏状态参数正确与否进行判断
        if(id == null || (type != 0 && type != 1 ))return paramError;
        //2.更新状态
        //获取当前用户信息
        Integer uid = WmThreadLocalUtils.getUser().getId();
        update(Wrappers.<WmMaterial>lambdaUpdate().set(WmMaterial::getIsCollection,type)
                .eq(WmMaterial::getId,id).eq(WmMaterial::getUserId,uid));
        return okResult;
    }
}
